package com.iflytek.uoamp.agent.monitor.find.imp;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.Program;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.ProgramType;
import com.iflytek.uoamp.agent.monitor.find.Finder;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;

/**
 * @author gaowei
 * lib的监控项自动添加
 */
public class FindLibMonitorItem implements Finder{

	private Lock lock = new ReentrantLock();
	private static Map<String,String[]> map = new  HashMap<String,String[]>();
	
	/**
	 * add lib info to map cache.chache hash by ip and cp name
	 * */
	public void add(String ip,String cp){
		lock.lock();
		try{
			if(!map.containsKey(ip+cp)){
				map.put(ip+cp, new String[]{ip,cp});
			}
		}finally{
			lock.unlock();
		}
	}
	
	/**
	 * when get cache map,this function will clean the cache and return program list
	 * */
	@Override
	public List<Program> getMonitorItems() {
		Map<String,String[]> temp = null;
		lock.lock();
		try{
			temp = new HashMap<String,String[]>(map);
			map.clear();
		}finally{
			lock.unlock();
		}
		
		List<Program> list = new LinkedList<Program>();
		Iterator<Entry<String, String[]>> it = temp.entrySet().iterator();
		while(it.hasNext()){
			Entry<String, String[]> entry = it.next();
			Program cprogram = new Program();
			cprogram.setCpname(entry.getValue()[1]);
			cprogram.setIp(entry.getValue()[0]);
			cprogram.setType(ProgramType.LIB);
    		//getMAC
    		cprogram.setMac(MCAgentConfig.getInstance().getMonitoredPointMAC());
    		//get机房名称
    		cprogram.setHostroom(MCAgentConfig.getInstance().getEngineRoomName());
			//get主机名称
    		cprogram.setHostname(MCAgentConfig.getInstance().getMonitoredHostName());
			list.add(cprogram);
		}
		
		return list;
	}
	
}
